{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from adalflow.components.agent import ReActAgent\n",
    "from adalflow.core import Generator, ModelClientType, ModelClient\n",
    "from adalflow.utils import setup_env\n",
    "\n",
    "# get_logger(level=\"DEBUG\")\n",
    "\n",
    "setup_env()\n",
    "\n",
    "\n",
    "# Define tools\n",
    "def multiply(a: int, b: int) -> int:\n",
    "    \"\"\"\n",
    "    Multiply two numbers.\n",
    "    \"\"\"\n",
    "    return a * b\n",
    "\n",
    "\n",
    "async def add(a: int, b: int) -> int:\n",
    "    \"\"\"\n",
    "    Add two numbers.\n",
    "    \"\"\"\n",
    "    return a + b\n",
    "\n",
    "\n",
    "def divide(a: float, b: float) -> float:\n",
    "    \"\"\"\n",
    "    Divide two numbers.\n",
    "    \"\"\"\n",
    "    return float(a) / b\n",
    "\n",
    "\n",
    "llama3_model_kwargs = {\n",
    "    \"model\": \"llama3-8b-8192\",  # llama3 70b works better than 8b here.\n",
    "    \"temperature\": 0.0,\n",
    "}\n",
    "gpt_model_kwargs = {\n",
    "    \"model\": \"gpt-3.5-turbo\",\n",
    "    \"temperature\": 0.0,\n",
    "}\n",
    "\n",
    "\n",
    "def test_react_agent(model_client: ModelClient, model_kwargs: dict):\n",
    "    tools = [multiply, add, divide]\n",
    "    queries = [\n",
    "        # \"What is the capital of France? and what is 465 times 321 then add 95297 and then divide by 13.2?\",\n",
    "        \"Give me 5 words rhyming with cool, and make a 4-sentence poem using them\",\n",
    "    ]\n",
    "    # define a generator without tools for comparison\n",
    "\n",
    "    generator = Generator(\n",
    "        model_client=model_client,\n",
    "        model_kwargs=model_kwargs,\n",
    "    )\n",
    "\n",
    "    react = ReActAgent(\n",
    "        max_steps=6,\n",
    "        add_llm_as_fallback=True,\n",
    "        tools=tools,\n",
    "        model_client=model_client,\n",
    "        model_kwargs=model_kwargs,\n",
    "    )\n",
    "    # print(react)\n",
    "\n",
    "    for query in queries:\n",
    "        print(f\"Query: {query}\")\n",
    "        agent_response = react.call(query)\n",
    "        llm_response = generator.call(prompt_kwargs={\"input_str\": query})\n",
    "        print(f\"Agent response: {agent_response}\")\n",
    "        print(f\"LLM response: {llm_response}\")\n",
    "        print(\"\")\n",
    "\n",
    "\n",
    "def test_react_agent_use_examples(model_client: ModelClient, model_kwargs: dict):\n",
    "    tools = [multiply, add, divide]\n",
    "    queries = [\n",
    "        \"What is the capital of France? and what is 465 times 321 then add 95297 and then divide by 13.2?\",\n",
    "        \"Give me 5 words rhyming with cool, and make a 4-sentence poem using them\",\n",
    "    ]\n",
    "\n",
    "    from adalflow.core.types import FunctionExpression\n",
    "\n",
    "    # add examples for the output format str\n",
    "    example_using_multiply = FunctionExpression.from_function(\n",
    "        func=multiply,\n",
    "        thought=\"Now, let's multiply two numbers.\",\n",
    "        a=3,\n",
    "        b=4,\n",
    "    )\n",
    "    react = ReActAgent(\n",
    "        max_steps=6,\n",
    "        add_llm_as_fallback=True,\n",
    "        tools=tools,\n",
    "        model_client=model_client,\n",
    "        model_kwargs=model_kwargs,\n",
    "        examples=[example_using_multiply],\n",
    "    )\n",
    "\n",
    "    print(react)\n",
    "\n",
    "    # see the output format\n",
    "    react.planner.print_prompt()\n",
    "\n",
    "    for query in queries:\n",
    "        print(f\"Query: {query}\")\n",
    "        agent_response = react.call(query)\n",
    "        print(f\"Agent response: {agent_response}\")\n",
    "        print(\"\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_react_agent(ModelClientType.GROQ(), llama3_model_kwargs)\n",
    "    test_react_agent(ModelClientType.OPENAI(), gpt_model_kwargs)\n",
    "    print(\"Done\")\n",
    "\n",
    "    test_react_agent_use_examples(ModelClientType.GROQ(), llama3_model_kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# test async\n",
    "\n",
    "import asyncio\n",
    "import time\n",
    "\n",
    "\n",
    "def is_running_in_event_loop() -> bool:\n",
    "    try:\n",
    "        loop = asyncio.get_running_loop()\n",
    "        if loop.is_running():\n",
    "            return True\n",
    "        else:\n",
    "            return False\n",
    "    except RuntimeError:\n",
    "        return False\n",
    "\n",
    "\n",
    "def sync_func():\n",
    "    time.sleep(1)\n",
    "    print(\"Sync function\")\n",
    "\n",
    "\n",
    "def execute():\n",
    "    if is_running_in_event_loop():\n",
    "        print(\"Running in event loop\")\n",
    "        try:\n",
    "            result = asyncio.to_thread(sync_func)\n",
    "            print(\"Result\", result)\n",
    "        except RuntimeError:\n",
    "            print(\"Runtime error\")\n",
    "            sync_func()\n",
    "    else:\n",
    "        sync_func()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running in event loop\n",
      "Result <coroutine object to_thread at 0x1351c1e40>\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/h8/nhgbdr4d18x2r49j4pk5z6gw0000gn/T/ipykernel_98631/3325042598.py:1: RuntimeWarning: coroutine 'to_thread' was never awaited\n",
      "  execute()\n",
      "RuntimeWarning: Enable tracemalloc to get the object allocation traceback\n"
     ]
    }
   ],
   "source": [
    "execute()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "my-project-kernel",
   "language": "python",
   "name": "my-project-kernel"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
